/**
 * 
 */
package masterlink.futures.dao;

import java.util.ArrayList;
import java.util.List;

import masterlink.futures.vo.Account;
import masterlink.futures.vo.EquityHis;
import masterlink.futures.vo.Fuhivabal;
import masterlink.futures.vo.Group;

import org.springframework.stereotype.Repository;

import baytony.util.Util;

/**
 * @author tonyyang
 *
 */
@Repository
public class EquityHisDao extends TimesTenTemplateDao{
	
	private static final String FIND_BY_GROUP="select {b.*},{c.*} from greeks_limit a,fuminv b,"+ 
										"(select * from fuhivabal where date1>=? and date1<=?) c "+
										"where a.broker=b.broker_id and a.account=b.acno " +
										"and a.broker=c.broker_id(+) and a.account=c.acno(+) " +
										"and a.id=? order by c.acno, c.date1";
	private static final String FIND_BY_ACCOUNT="select {b.*},{c.*} from greeks_limit a,fuminv b,"+ 
										"(select * from fuhivabal where date1>=? and date1<=?) c "+
										"where a.broker=b.broker_id and a.account=b.acno " +
										"and a.broker=c.broker_id(+) and a.account=c.acno(+) " +
										"and a.id=? and a.account=? order by c.acno, c.date1";
	
	@SuppressWarnings("unchecked")
	public List<EquityHis> findByGroup(Group group,Long start,Long end){
		log.trace("findByGroup {} start : {} end :"+end,group,start);
		if(group!=null&&start!=null&&end!=null){
			return create((List<Object[]>) executeQuery(createSqllQuery(FIND_BY_GROUP).addEntity("b", Account.class).addEntity("c",Fuhivabal.class)
					,start,end,group.getId()));
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public EquityHis findByAccount(Group group,Account acc,Long start,Long end){
		log.trace("findByGroup {} with acc : {}:",group,acc);
		log.trace("start : {}  end : {}:",start,end);
		if(group!=null&&acc!=null&&start!=null&&end!=null){
			List<EquityHis> all= create((List<Object[]>) executeQuery(createSqllQuery(FIND_BY_ACCOUNT).addEntity("b", Account.class).addEntity("c",Fuhivabal.class)
					,start,end,group.getId(),acc.getId().getAcno()));
			if(!Util.isEmptyList(all)){
				return all.get(0);
			}
		}
		return null;
	}
	
	private List<EquityHis> create(List<Object[]> all){
		List<EquityHis> res=new ArrayList<EquityHis>();
		if(!Util.isEmptyList(all)){
			for(Object[] o:all){
				Account acc=(Account)evict(o[0]);
				Fuhivabal cc=(Fuhivabal)evict(o[1]);
				EquityHis e=new EquityHis(acc);
				if(res.contains(e)){
					res.get(res.indexOf(e)).addFuhivabal(cc);
				}else{
					e.addFuhivabal(cc);
					res.add(e);
				}
			}
		}
		log.trace("{} of EquityHis was found.",res.size());
		return res;
	}

	
}
